<script setup>
import { ref, onMounted, computed } from 'vue'
import { sessionApi, pageTagApi, saveTagApi, delTagsApi } from '@/common/api'
import router from '@/common/router'
import Note from '@/components/notify'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import { CScrollbar } from 'c-scrollbar'
import Pager from '@/components/pagination/UbtPager.vue'
import { formatDate } from "@/common/filter"

// 自动加载，判断权限
onMounted(() => {
  checkAuth()
})

// 字典标签 1表示资讯标签，2表示视频资讯标签，3表示商家标签，4表示商品标签
const tagKind = 2

const procAuth = ref({
  addAuth: false,
  delAuth: false,
  edtAuth: false
})
// checkAuth 获取权限
const checkAuth = async () => {
  const res = await sessionApi()
  if (res.code === 200) {
    const userBtnCode = res.data.btnCodes
    procAuth.value = {
      addAuth: userBtnCode.indexOf('1002020201') !== -1,
      delAuth: userBtnCode.indexOf('1002020202') !== -1,
      edtAuth: userBtnCode.indexOf('1002020203') !== -1
    }
    list(0, 1)
  } else {
    Msg({ kind: 'error', txt: res.msg })
    router.replace('/login')
  }
}

const schObj = {
  schName: '',
  kind: tagKind,
  offset: 0,
  limit: 20
}
const schRef = ref(schObj)
const total = ref(0)
const curPage = ref(1)
const tagList = ref([])
const hasData = ref(false)
const checkList = ref([])
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageTagApi(schRef.value)
  if(res.code === 200 && res.data) {
    hasData.value = true
    total.value = res.data.total
    tagList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// 选择效果实现
const idList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    tagList.value.forEach(item => {
      idList.value.push(item.tagId)
      checkList.value.push(true)
    })
  } else {
    tagList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, tagId) => {
  if(!checkList.value[idx]) {
    idList.value.push(tagId)
  } else {
    const index = idList.value.findIndex(id => {
      if(id === tagId){
        return true
      }
    })
    idList.value.splice(index, 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const tagObj = {
  tagId: '',
  tagName: '',
  kind: tagKind,
}
const tagForm = ref(tagObj)
// add 新增
const showModal = ref(false)
const add = () => {
  showModal.value = true
}
// update 修改
const update = async (tagId, tagName) => {
  showModal.value = true
  tagForm.value.tagId = tagId
  tagForm.value.tagName = tagName
}
// save 保存提交
const save = async () => {
  let tagName = tagForm.value.tagName
  if(tagName === '' || tagName.length > 80) {
    Msg({ kind: 'warn', txt: '标签的名称不能为空，且长度不超过80个字符' })
    return
  }
  const res = await saveTagApi(tagForm.value)
  if(res.code === 200) {
    closeModal()
    list(0, 1)
    Note({ kind: 'success', title: '成功', txt: '恭喜您，标签信息保存成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// closeModal 关闭弹出层，并重置表单标签
const closeModal = () => {
  showModal.value = false
  tagForm.value = {
    tagId: '',
    tagName: '',
    kind: tagKind,
  }
}

// deletes 批量删除标签
const deletes = async() => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再操作！' })
    return
  }
  Confirm('确定要删除选中的标签吗？').then(() => {
    delTags()
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的标签！" })
  })
}
// delTags 删除标签实现，分离出来防止调用时异步报错
const delTags = async () => {
  let tagIds = idList.value.join(',')
  const res = await delTagsApi({ tagIds, kind: tagKind })
  if(res.code === 200) {
    list(0, 1)
    Note({ kind: 'success', title: '成功', txt: '恭喜您，标签信息删除成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// fmtDate 时间戳转时间
const fmtDate = computed(() => {
  return (time, kind) => {
    let date = new Date(time*1000)
    return formatDate(date, kind)
  }
})
</script>

<template>
  <div class="a">
    <!-- 头部标签 -->
    <div class="b">
      <div v-if="procAuth.addAuth" class="btn-p" title="新增" @click="add()"><i class="iconfont doc_text"></i> 新增</div>
      <div v-if="procAuth.delAuth" class="btn-d" title="删除" @click="deletes()"><i class="iconfont trash"></i> 删除</div>
      <div class="btn-r" title="筛选" @click="search()"><i class="iconfont search"></i></div>
      <div class="btn-r" title="刷新" @click="list(0, 1)"><i class="iconfont arrow__circlepath"></i></div>
    </div>
    <!-- 中部标签 -->
    <div class="c" v-if="schShow">
      <div class="d"><input type="text" v-model="schRef.schName" placeholder="请输入名称的关键字" class="e" /></div>
      <div class="btn-p" @click="list(0, 1)"><i class="iconfont search"></i> 筛选</div>
    </div>
    <div class="f" v-if="hasData">
      <table>
        <tr>
          <th style="width: 10%;"><i @click="checkAll()" :class="['iconfont', allCheck ? 'checkmark_square_fill chked' : 'app chk']"></i></th>
          <th style="width: 40%;">名称</th>
          <th style="width: 30%;">时间</th>
          <th style="width: 20%;">操作</th>
        </tr>
        <tr v-for="(curTag, index) in tagList" :key="curTag.tagId" class="tr-style">
          <td class="txt-center"><i @click="checkCurId(index, curTag.tagId)" :class="['iconfont', checkList[index] ? 'checkmark_square_fill chked' : 'app chk']"></i></td>
          <td class="txt-center">{{curTag.tagName}}</td>
          <td class="txt-center">{{fmtDate(curTag.addTime, 2)}}</td>
          <td class="txt-center">
            <span v-if="procAuth.edtAuth" class="cl-blue" title="修改" @click="update(curTag.tagId, curTag.tagName)"><i class="iconfont square_pencil"></i> 修 改</span>
          </td>
        </tr>
      </table>
      <Pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 600px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont doc_text fs20"></i> 保存标签信息</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont xmark fs20"></i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>标签名称</div>
                <div><input type="text" v-model="tagForm.tagName" maxlength="80" placeholder="请输入标签名称" class="txt" /></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-p" @click="save()"><i class="iconfont today_fill"></i> 保存</div>
              <div class="btn-d" @click="closeModal()"><i class="iconfont arrowshape_turn_up_left"></i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
  </div>
</template>

<style scoped>
.a {width: 100%; height: 100%;}
.b {padding: 10px 20px; display: flex; display: -webkit-flex;}
.c {margin: 0 10px 10px 10px; border: 1px solid #CCC; display: flex; display: -webkit-flex; padding: 15px;}
.d {flex-grow: 1;}
.e {width: 230px; padding: 8px;}
.f {background-color: #FFF;}
</style>
